package com.team8.system.service.service;

import com.team8.system.pojo.*;
import com.team8.system.service.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

@Service
public class SystemService {

    @Autowired
    private DicCodeDao dicCodeDao;

    @Autowired
    private PackageInfoDao packageInfoDao;

    @Autowired
    private CheckInResultDao checkInResultDao;

    @Autowired
    private CheckInTimeDao checkInTimeDao;

    @Autowired
    private FlightInfoDao flightInfoDao;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final Random random = new Random();

    private final ThreadLocal<SimpleDateFormat> simpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMddHHmmss");
        }
    };

    // 机场的类别是 1
    public void handleBASEAPUE(InputStream xmlStream) throws Exception {

        //创建SAXReader
        SAXReader sax = new SAXReader();
        //获得文档对象
        Document read = sax.read(xmlStream);
        //获得根元素
        Element root = read.getRootElement();

        Element father = root.element("APOT");

        String sanzima = father.element("CODE").getText().trim();
        String sizima = father.element("FRCD").getText().trim();
        String name = father.element("CNNM").getText().trim();

        DicCode dicCode = new DicCode();

        Example example = new Example(DicCode.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("threeCharacterCode", sanzima);

        List<DicCode> dicCodes = dicCodeDao.selectByExample(example);

        if (CollectionUtils.isEmpty(dicCodes)) {
            dicCode.setFourCharacterCode(sizima);
            dicCode.setThreeCharacterCode(sanzima);
            dicCode.setName(name);
            dicCode.setType("1");
            dicCodeDao.insert(dicCode);
        } else {

        }

        xmlStream.close();
    }

    public void handleDFMEBLLS(InputStream xmlStream) throws Exception {
        SimpleDateFormat format = this.simpleDateFormat.get();
        //创建SAXReader
        SAXReader sax = new SAXReader();
        //获得文档对象
        Document read = sax.read(xmlStream);
        //获得根元素
        Element root = read.getRootElement();
        Element DFLT = root.element("DFLT");
        String ffid = DFLT.element("FFID").getText();
        Element BELT = DFLT.element("BLLS").element("BELT");
        String code = BELT.element("CODE").getText();
        String id = BELT.element("ID").getText();
        String estr = BELT.element("ESTR").getText();
        if (StringUtils.isBlank(estr))
            estr = BELT.element("RSTR").getText();
        String eend = BELT.element("EEND").getText();
        if (StringUtils.isBlank(eend))
            eend = BELT.element("REND").getText();

        Example example = new Example(PackageInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("ffid", ffid);
        String btsc = BELT.element("BTSC").getText();
        List<PackageInfo> packageInfos = packageInfoDao.selectByExample(example);
        PackageInfo packageInfo = new PackageInfo();
        if (CollectionUtils.isEmpty(packageInfos)) {
            packageInfo.setPacgId(id);
            if (!StringUtils.isBlank(eend))
                packageInfo.setEndTime(format.parse(eend));
            if (!StringUtils.isBlank(estr))
                packageInfo.setStartTime(format.parse(estr));
            packageInfo.setFfid(ffid);
            packageInfo.setTerminal(btsc);
            packageInfo.setTurntableNumber(code);

            packageInfoDao.insert(packageInfo);
        } else {
            packageInfo = packageInfos.get(0);

            if (StringUtils.isBlank(packageInfo.getTerminal())) {
                packageInfo.setTerminal(btsc);
            }
            if (packageInfo.getStartTime() == null) {
                if (!StringUtils.isBlank(estr))
                    packageInfo.setStartTime(format.parse(estr));
            }
            if (packageInfo.getEndTime() == null) {
                if (!StringUtils.isBlank(estr))
                    packageInfo.setEndTime(format.parse(estr));
            }
            packageInfoDao.updateByExample(packageInfo, example);
        }


        xmlStream.close();
    }

    public void handleDFMECKIE(InputStream xmlStream) throws Exception {
        SimpleDateFormat format = this.simpleDateFormat.get();
        //创建SAXReader
        SAXReader sax = new SAXReader();
        //获得文档对象
        Document read = sax.read(xmlStream);
        //获得根元素
        Element root = read.getRootElement();

        Element dflt = root.element("DFLT");
        Element ffid = dflt.element("FFID");
        Element fcrs = dflt.element("FCRS");        // 开始值机时间

        Example example = new Example(CheckInTime.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("fild", ffid);

        List<CheckInTime> CheckInTimes = checkInTimeDao.selectByExample(example);

        CheckInTime checkInTime = new CheckInTime();
        if (CollectionUtils.isEmpty(CheckInTimes)) {
            if (!StringUtils.isBlank(fcrs.getText()))
                checkInTime.setBeginTime(format.parse(fcrs.getText()));
            checkInTime.setFfid(ffid.getText());

            checkInTimeDao.insert(checkInTime);
        } else {
            checkInTime = CheckInTimes.get(0);
            if (!StringUtils.isBlank(fcrs.getText()))
                checkInTime.setBeginTime(format.parse(fcrs.getText()));

            checkInTimeDao.updateByExample(checkInTime, example);

        }
        xmlStream.close();

    }

    public void handleDFMECKLS(InputStream xmlStream) throws Exception {

        SimpleDateFormat format = this.simpleDateFormat.get();
        //创建SAXReader
        SAXReader sax = new SAXReader();
        //获得文档对象
        Document read = sax.read(xmlStream);
        //获得根元素
        Element root = read.getRootElement();
        Element dflt = root.element("DFLT");
        Element ffid = dflt.element("FFID");
        Element ckls = dflt.element("CKLS");
        Element fces = ckls.element("FCES");
        Element fcee = ckls.element("FCEE");
        Element fcdp = ckls.element("FCDP");


        Example example = new Example(CheckInTime.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("ffid", ffid.getText());

        List<CheckInTime> checkInTimes = checkInTimeDao.selectByExample(example);


        CheckInTime checkInTime = new CheckInTime();
        if (CollectionUtils.isEmpty(checkInTimes)) {
            checkInTime.setFfid(ffid.getText());
            if (!StringUtils.isBlank(fces.getText()))
                checkInTime.setBeginTime(format.parse(fces.getText()));
            if (!StringUtils.isBlank(fcee.getText()))
                checkInTime.setEndTime(format.parse(fcee.getText()));
            checkInTime.setWindowId(fcdp.getText());
            checkInTimeDao.insert(checkInTime);
        } else {
            checkInTime = checkInTimes.get(0);
            if (checkInTime.getBeginTime() == null) {
                if (!StringUtils.isBlank(fces.getText()))
                    checkInTime.setBeginTime(format.parse(fces.getText()));
            }
            if (checkInTime.getEndTime() == null) {
                if (!StringUtils.isBlank(fcee.getText()))
                    checkInTime.setEndTime(format.parse(fcee.getText()));
            }
            if (StringUtils.isBlank(checkInTime.getWindowId())) {
                checkInTime.setWindowId(fcdp.getText());
            }
            checkInTimeDao.updateByExample(checkInTime, example);

        }
        xmlStream.close();
    }

    @Autowired
    private FlightSegsDao flightSegsDao;
    public void handleDFOEDFDL(InputStream xmlStream) throws Exception {
        SimpleDateFormat format = this.simpleDateFormat.get();
        //创建SAXReader
        SAXReader sax = new SAXReader();
        //获得文档对象
        Document read = sax.read(xmlStream);
        //获得根元素
        Element root = read.getRootElement();
        List dflts = root.elements("DFLT");

        Iterator dfltsIterator = dflts.iterator();
        while (dfltsIterator.hasNext()) {
            Element dflt = (Element) dfltsIterator.next();
            Element ffid = dflt.element("FFID");
            System.out.println(ffid.getText());
            Element airl = dflt.element("AIRL");
            List arpts = airl.elements("ARPT");
            int size = arpts.size();

            int ticketNum = random.nextInt(100) + 100;



            FlightSegs flightSegs = new FlightSegs();
            flightSegs.setFfid(ffid.getText());
            flightSegs.setMax(size - 1);
            flightSegsDao.insert(flightSegs);

            for (int i = 0; i < size - 1; i++) {
                Element beginARPT = (Element) arpts.get(i);
                for(int j = i + 1; j < size; j++){
                    Element endARPT = (Element) arpts.get(j);
                    FlightInfo flightInfo = new FlightInfo();
                    flightInfo.setFfid(ffid.getText());
                    String startport = beginARPT.element("APCD").getText();
                    String endport = endARPT.element("APCD").getText();

                    List<DicCode> dicCodes = dicCodeDao.selectNameByTcc(startport.trim());

                    if(!CollectionUtils.isEmpty(dicCodes)){
                        startport = dicCodes.get(0).getName();
                    }
                    flightInfo.setStartPort(startport);

                    List<DicCode> dicCodes1 = dicCodeDao.selectNameByTcc(endport.trim());
                    if(!CollectionUtils.isEmpty(dicCodes1))
                        endport = dicCodes1.get(0).getName();
                    flightInfo.setEndPort(endport);

                    if (!StringUtils.isBlank(beginARPT.element("FPTT").getText())) {
                        flightInfo.setStartTime(format.parse(beginARPT.element("FPTT").getText()));
                    }

                    if (!StringUtils.isBlank(endARPT.element("FPLT").getText())) {
                        flightInfo.setEndTime(format.parse(endARPT.element("FPLT").getText()));
                    }

                    flightInfo.setStartSeg(String.valueOf(i));
                    flightInfo.setEndSeg(String.valueOf(j));
                    flightInfo.setTicketNum(ticketNum);
                    flightInfoDao.insert(flightInfo);
                    amqpTemplate.convertAndSend("as.es.exchange", "es.flightinfo.insert", flightInfo);

                }
            }
        }
        xmlStream.close();
    }
}